self.addEventListener("install", (event) => {
  /**
   * 安装事件处理程序
   * @type {ExtendableEvent}
   */ (event).waitUntil(
    caches
      .open("v1")
      .then((cache) =>
        cache.addAll([
          "/",
          "/index.html",
          "/style.css",
          "/app.js",
          "/image-list.js",
          "/star-wars-logo.jpg",
          "/gallery/bountyHunters.jpg",
          "/gallery/myLittleVader.jpg",
          "/gallery/snowTroopers.jpg",
        ]),
      ),
  );
});

self.addEventListener("fetch", async (event) => {
  /** @type {FetchEvent} */ (event).respondWith(resp());
  /**
   * 响应事件处理程序
   * @returns {Promise<Response>}
   */
  async function resp() {
    const response = await caches.match(
      /** @type {FetchEvent} */ (event).request,
    );
    if (response !== undefined) {
      return response;
    }
    return await fetch(/** @type {FetchEvent} */ (event).request)
      .then((response) => {
        // response may be used only once
        // we need to save clone to put one copy in cache
        // and serve second one
        const responseClone = response.clone();

        caches
          .open("v1")
          .then((cache) =>
            cache.put(/** @type {FetchEvent} */ (event).request, responseClone),
          );
        return response;
      })
      .catch(
        () =>
          /** @type { Promise<Response>}*/ (
            caches.match("/gallery/myLittleVader.jpg")
          ),
      );
  }
});
